<?php
namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\Model;
use \think\Session;
use think\Request;

/**
 * 借款控制器
*/
class Borrow extends CommonController
{
	// 审核借款
	public function listBorrow()
	{
		$borrowSql = "select * from borrow inner join user on borrow.uid = user.userId";

		$listBorrow = Db::query($borrowSql);

		$listBorrow = $this->loop($listBorrow);

		return $this->fetch('listBorrow',['listBorrow'=>$listBorrow]);	
	}

	// 审核借款
	public function auditBorrow()
	{
		if(request()->isPost())
		{
			$userId = input('post.userId');

			$repayStatus = input('post.status');

			$repayMoney = input('post.repayMoney');

			$bid = input('post.bid');

			if($repayStatus == 2)
			{
				Db::table('borrow')->update(['repayStatus'=>2,'bid'=>$bid]);

				$userMoney = Db::table('user')->where('userId',$userId)->value('money');

				$userMoney = $userMoney+$repayMoney;

				Db::table('user')->update(['money'=>$userMoney,'userId'=>$userId]);
			}
			else
			{
				Db::table('borrow')->update(['repayStatus'=>3,'bid'=>$bid]);
			}

			echo json_encode(1);
		}
		else
		{
			$borrowSql = "select * from borrow as b inner join user as u on b.uid = u.userId where b.repayStatus = 1";

			$UnauditedBorrow = Db::query($borrowSql);

			$UnauditedBorrow = $this->loop($UnauditedBorrow);

			return $this->fetch('auditBorrow',['UnauditedBorrow'=>$UnauditedBorrow]);
		}
	}

	// 循环列表
	public function loop($listBorrow)
	{
		foreach ($listBorrow as $k => $v) 
		{
			if ($v['long'] == 90) {
				$listBorrow[$k]['long'] = '3个月';
			}else if ($v['long'] == 180){
				$listBorrow[$k]['long'] = '6个月';
			}else{
				$listBorrow[$k]['long'] = '12个月';
			}
			// 判断是审核状态
			if ($v['repayStatus'] == 1) {
				$listBorrow[$k]['repayStatus'] = '未审核';
			}else if ($v['repayStatus'] == 2){
				$listBorrow[$k]['repayStatus'] = '审核通过';
			}else{
				$listBorrow[$k]['repayStatus'] = '审核未通过';
			}

			if ($v['repayment'] == 1) {
				$listBorrow[$k]['repayment'] = '等额本金';
			}else if ($v['repayment'] == 2){
				$listBorrow[$k]['repayment'] = '等额本息';
			} else {
				$listBorrow[$k]['repayment'] = '一次性还款';
			}
			$listBorrow[$k]['time'] = date('Y-m-d H:i:s',$v['time']);
		}
		return $listBorrow;
	}
}